package vip.xiaonuo.common.wechat;

import vip.xiaonuo.common.util.CommonDateUtil;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

public class MailSender {
    public static void sendWithAttachment(
            String smtpHost,
            String username,
            String password,
            String toAddress,
            String attachmentPath) throws Exception {

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
        message.setSubject(CommonDateUtil.getPreviousDayStr() + "手机号拨打次数大于5次的坐席");

        Multipart multipart = new MimeMultipart();

        // 添加正文
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText("附件是呼叫数据统计报表，请查收。");
        multipart.addBodyPart(textPart);

        // 添加附件
        MimeBodyPart attachmentPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentPath);
        attachmentPart.setDataHandler(new DataHandler(source));
        attachmentPart.setFileName(CommonDateUtil.getPreviousDayStr() + " 手机号拨打次数大于5次的坐席.xlsx");
        multipart.addBodyPart(attachmentPart);

        message.setContent(multipart);
        Transport.send(message);
    }
}
